<!-- 生产批次查询 -->
<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="queryPageList(), searchPage()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">批次编号</div>
            <el-input v-model="mnecode" clearable />
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">养殖鱼塘</div>
            <el-select filterable clearable v-model="fishPondId" filterable clearable>
              <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                :value="item.fishPondId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">养殖品种</div>
            <el-select filterable clearable v-model="fishVarietyId" filterable clearable>
              <el-option v-for="(item, index) in FishVarietyData" :key="index" :label="item.varietyName"
                :value="item.fishVarietyId" />
            </el-select>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">封塘日期</div>
            <el-date-picker v-model="closePondDateTimeList" type="daterange" placeholder="选择日期" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" clearable />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:btnsBar>
      <ActionBar :export-active="true" :hasExport="true" :hasAdd="false" :hasDel="false" :page-no="162" @add="add"
        @del="del" @exportFile="exportFile" />
    </template>
    <template v-slot:categoryBox>
      <CategoryBar v-show="routerPath !== '/production-batch-query-sr'" :categoryList="categoryList"
        :routerIndex="routerIndex" @categoryBar="categoryBar" />
    </template>
    <template v-slot:content>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border
        height="calc(100% - 50px)" :row-key="row => {
          return row.productionBatchId;
        }
          " @selection-change="handleSelectionChange" @select="select" @select-all="selectAll">
        <!-- <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="(row) => { return !row.selectable }" /> -->
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.productionBatchId ? scoped.$index + 1 : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="mnecode" label="批次编号" min-width="180" />
        <el-table-column prop="productionBatchCode" label="码单号" />
        <el-table-column prop="breedTypeName" label="养殖类型" />
        <el-table-column prop="varietyName" label="养殖鱼种" />
        <el-table-column prop="pondName" label="养殖鱼塘" />
        <el-table-column prop="pondRatio" label="鱼塘占比(%)">
          <template v-if="scoped.row.pondRatio" slot-scope="scoped">
            <span>{{ scoped.row.pondRatio }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="供应商">
          <template v-if="scoped.row.pondRatio" slot-scope="scoped">
            <span>{{ scoped.row.supplier ? processName(scoped.row.supplier) : '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="批次剩余数量（尾）" width="120" />
        <el-table-column prop="avgWeight" label="均重（斤）" />
        <el-table-column prop="weight" label="总重（斤）" />
        <el-table-column prop="inputNum" label="投塘鱼数（尾）" />
        <el-table-column prop="transferNum" label="转分塘尾数（尾）">
          <template v-if="scoped.row.productionBatchId" slot-scope="scoped">
            <div class="table-btns-box">
              <span v-show="scoped.row.transferNum == 0">--</span>
              <span v-show="scoped.row.transferNum !== 0"
                :style="scoped.row.transferNum > 0 ? { color: '#42b983' } : { color: '#e6a700' }">
                {{ scoped.row.transferNum > 0 ? scoped.row.transferNum + ' ' + '↑' : scoped.row.transferNum + ' ' + '↓' }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="produceLiveNum" label="产出活鱼数（尾）" />
        <el-table-column prop="produceSecondaryNum" label="产出次鱼数（尾）" />
        <el-table-column prop="deadNum" label="直鱼数（尾）" />
        <el-table-column prop="buildDateTime" label="创建日期" />
        <el-table-column prop="closePondDateTime" label="封塘日期">
          <template v-if="scoped.row.productionBatchId" slot-scope="scoped">
            <div class="table-btns-box">
              {{ scoped.row.closePondDateTime ? scoped.row.closePondDateTime : '--' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="status == 'COMPLETED'" prop="completeDateTime" label="完成日期" />
        <el-table-column v-if="status == 'COMPLETED'" label="完成方式" min-width="120">
          <template v-if="scoped.row.productionBatchId" slot-scope="scoped">
            <p>{{ status == 'COMPLETED' ? (scoped.row.clearCompleteFlag ? '清塘自动完成' : '手动完成') : '' }}</p>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="status == 'UN_COMPLETE'" label="操作" width="150">
          <template v-if="scoped.row.productionBatchId" slot-scope="scoped">
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(scoped.row)">
                <p>修改</p>
              </div>
            </div>
          </template>
        </el-table-column> -->
      </el-table>
      <ExportBtn ref="ExportBtn" :btnName="'批次导出'" :apiName="'productionBatchExport'" :searchObj="searchObj"></ExportBtn>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changeCurrentPage="changeCurrentPage" />
      <AddEditDialog ref="addEditDialog" :now-chance-stau="nowChanceStau" :title-text="titleText"
        :edit-object="editObject" :show.sync="showAddEditDialog" @closeDialog="closeDialog" @cancelDialog="cancel" />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import CategoryBar from "@/components/CategoryBar";
import ExportBtn from "@/components/ExportBtn";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from 'vuex';

import BatchMangeApi from "@/api/batch-mange"
import FishVarietyApi from "@/api/basic-info-manage/fishVariety"
import FishPondApi from "@/api/basic-info-manage/fishPond"
import { color } from "echarts";
export default {
  name: 'BatchCreate',
  components: { ActionBar, Pagination, BaseMainSlot, AddEditDialog, CategoryBar, ExportBtn },
  mixins: [mymixin],
  data () {
    return {
      searchObj: {},
      routerIndex: 0,
      mnecode: "",//批次编号
      productionBatchCode: "",//码单号
      fishPondId: "",//养殖鱼塘ID
      fishVarietyId: "",//养殖品种ID
      closePondDateTimeList: [],//封塘时间
      checkedIdList: [],
      fishPondList: [],//全部鱼塘
      FishVarietyData: [],//全部品种
      categoryList: [
        { id: 1, mark: 'status', name: "存塘", value: 'UN_COMPLETE' },
        { id: 2, mark: 'status', name: "清塘", value: 'COMPLETED' },
      ],//分类列表
      status: '',//批次状态
      showAddEditDialog: false,
      showEstimationDialog: false,
      activeName: '',
      routerPath: ''
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created () {
    console.log(this.$route)
    this.routerParams = this.$route.params ? this.$route.params : {}
    if (this.routerParams.status == 'COMPLETED') {
      this.routerIndex = 1
    } else {
      this.routerIndex = 0
    }
    this.routerPath = this.$route.path
    this.routerIndex = this.routerPath == '/production-batch-query-sr' ? 1 : 0

    console.log(this.routerIndex, '路由参数')
  },
  mounted () {
    this.queryFishVariety()
    this.queryFishPond()
  },
  methods: {
    searchPage () {
      this.currentPage = 1
      this.queryPageList();
    },
    exportFile () {
      this.$refs['ExportBtn'].downloadFile()
      console.log(this.$refs['ExportBtn'])
    },
    categoryBar (item) {
      this.status = ''
      if (item.mark === 'status') this.status = item.value;
      this.queryPageList()
      this.$nextTick(() => {
        this.$refs.tableData.doLayout()
      })
    },
    queryPageList () {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {}
      };
      if (this.mnecode) params.entity.mnecode = this.mnecode;
      if (this.productionBatchCode) params.entity.productionBatchCode = this.productionBatchCode;
      if (this.fishPondId) params.entity.fishPondId = this.fishPondId;
      if (this.fishVarietyId) params.entity.fishVarietyId = this.fishVarietyId;
      if (this.status !== '') params.entity.status = this.status;
      if (this.closePondDateTimeList && this.closePondDateTimeList.length > 0) {
        console.log(this.closePondDateTimeList)
        params.entity.closePondDateTimeStart = this.closePondDateTimeList[0] + " 00:00:00"
        params.entity.closePondDateTimeEnd = this.closePondDateTimeList[1] + " 23:59:59"
      }
      if (this.routerParams.productionBatchCode) {
        params.entity.productionBatchCode = this.routerParams.productionBatchCode
      }
      this.searchObj = JSON.parse(JSON.stringify(params.entity))
      BatchMangeApi.queryPageByCondition(params).then(res => {
        if (res.success === true) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
        this.routerParams = {}
      });
    },
    showEstimation () {
    },
    closeEstimationDialog () {
      this.showEstimationDialog = false
    },
    //查询可选鱼类品种
    queryFishVariety () {
      FishVarietyApi.queryByCondition().then(res => {
        this.FishVarietyData = res.data;
      })
    },
    //查询可选鱼塘
    queryFishPond () {
      FishPondApi.queryByCondition().then(res => {
        this.fishPondList = res.data;
      })
    },
    changeCurrentPage (currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    selectAll (list) {
      let notvalue = true
      list.forEach(item => {
        if (!item.productionBatchId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    select (list) {
      let notvalue = true
      list.forEach(item => {
        if (!item.productionBatchId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    handleSelectionChange (list) {
      this.checkedIdList = [];
      let notvalue = true
      let emptyList = []
      this.checkedIdList = list.map(item => {
        if (item.productionBatchId) {
          return item.productionBatchId
        } else {
          notvalue = false
          emptyList.push(item)
          return ""
        }
      });
      if (notvalue === false) {
        // this.$message.warning("不可选择空数据！");
        this.toggleNoSelection(emptyList)
        return
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 单个删除
    delOne (row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          BatchMangeApi.delById({ id: row.productionBatchId }).then(res => {
            if (res.success === true) {
              this.$message.success("删除成功!");
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 添加
    add () {
      this.nowChanceStau = 'add'
      this.titleText = "添加"
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true
    },
    // 修改
    edit (row) {
      if (row.productionBatchId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = 'edit'
        this.titleText = "修改"
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true
      } else {
        this.editObject = {}
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-range-separator {
  color: #333333;
}

.select-box-content-name {
  min-width: 80px;
}

.select-box-content {
  width: none !important;
}
</style>
